﻿using System.Web.Mvc;

namespace RecaptchaMvc {
	public static class ControllerExtensions {
		private static string TryGetValue(this IValueProvider valueProvider, string name) {
			ValueProviderResult result = valueProvider.GetValue(name);
			if(result != null)
				return result.AttemptedValue;
			return null;
		}
		public static IRecaptchaResponse TryValidateRecaptcha(this Controller controller, string privateKey) {
			return controller.TryValidateRecaptcha(privateKey, new DefaultValueProvider(controller.ControllerContext));
		}
		public static IRecaptchaResponse TryValidateRecaptcha(this Controller controller, string privateKey, IValueProvider valueProvider) {
			IRecaptchaRequest request = new RecaptchaRequest(privateKey, controller.HttpContext.Request.UserHostAddress);
			request.Challenge = valueProvider.TryGetValue("recaptcha_challenge_field");
			request.Response = valueProvider.TryGetValue("recaptcha_response_field");
			return controller.TryValidateRecaptcha(request);
		}
		public static IRecaptchaResponse TryValidateRecaptcha(this Controller controller, IRecaptchaRequest request) {
			return new RecaptchaValidator().Validate(request);
		}
		public static void ValidateRecaptcha(this Controller controller, string privateKey) {
			ControllerExtensions.Validate(controller.TryValidateRecaptcha(privateKey));
		}
		public static void ValidateRecaptcha(this Controller controller, string privateKey, IValueProvider valueProvider) {
			ControllerExtensions.Validate(controller.TryValidateRecaptcha(privateKey, valueProvider));
		}
		public static void ValidateRecaptcha(this Controller controller, IRecaptchaRequest request) {
			ControllerExtensions.Validate(controller.TryValidateRecaptcha(request));
		}
		private static void Validate(IRecaptchaResponse response) {
			if(!response.IsValid)
				throw new RecaptchaValidationException(response);
		}
	}
}